<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>axios默认配置</title>
  </head>
  <link rel="stylesheet" href="./css/bootstrap.min.css">
  <style>
    body {
      margin: 0 auto;
    }

    .div {
      margin: 40px auto;
      width: 1000px;
    }
  </style>

  <body>
    <div class="div">
      <h2>axios的默认配置</h2>
      <hr>
      <button type="button" class="btn btn-primary">发送get请求</button>
      <button type="button" class="btn btn-danger">发送post请求</button>
      <button type="button" class="btn btn-default">发送put请求</button>
      <button type="button" class="btn btn-info">发送delete请求</button>
    </div>
  </body>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    let btns = document.querySelectorAll(".btn");
    /*
    默认配置：
    */
    //  默认方法
    axios.defaults.method = "get";
    //  默认URL
    axios.defaults.baseURL = "http://localhost:3000";
    // 默认超时时长
    axios.defaults.timeout = 4000;
    // 默认参数
    axios.defaults.params = {
      id: 3000
    }

    // 1.发送get请求
    btns[0].addEventListener('click', function () {
      axios({
          url: "/posts",
        }).then((resource) => {
          console.log(resource);
        })
        .catch((error) => {
          console.log(error);
        })
    });

    //2.发送post的请求:添加一个
    btns[1].onclick = function () {
      axios({
          method: "post",
          url: "/posts",
          data: {
            name: "tom",
            title: "Java从入门到放弃"
          }
        })
        .then((resource) => {
          console.log(resource);
        })
        .catch((error) => {
          console.log(error);
        })
    }

    // 3.发送post的请求:修改记录
    btns[2].onclick = function () {
      axios({
          method: "put",
          url: "/posts/10",
          data: {
            title: "尤雨溪",
            name: "Vue"
          }
        })
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        })
    }

    // 4.发送delete请求:删除一条记录
    btns[3].onclick = function () {
      axios({
          method: "delete",
          url: "/posts/10",
        })
        .then((resource) => {
          console.log(resource);
        })
        .catch((err) => {
          console.log(err);
        })
    }
  </script>

</html>